package inits

import (
	"fmt"
	"github.com/elastic/go-elasticsearch/v8"
	"log"
	"shop/common/config"
	"shop/common/global"
	"strings"
)

var ESClient *elasticsearch.Client

// InitElasticsearch 初始化Elasticsearch客户端
// 功能: 根据配置创建并初始化Elasticsearch客户端实例
// 使用: 在应用启动时调用，确保ES客户端可用
func InitElasticsearch() {
	// 配置ES客户端
	cfg := elasticsearch.Config{
		Addresses: config.AppConf.Elasticsearch.Addresses,
		Username:  config.AppConf.Elasticsearch.Username,
		Password:  config.AppConf.Elasticsearch.Password,
	}

	// 创建ES客户端
	client, err := elasticsearch.NewClient(cfg)
	if err != nil {
		log.Fatalf("Error creating the client: %s", err)
	}

	// 测试连接
	res, err := client.Info()
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()

	if res.IsError() {
		log.Fatalf("Error: %s", res.Status())
	} else {
		log.Println("Elasticsearch connected successfully")
	}

	// 保存客户端实例到全局变量
	ESClient = client
	global.ESClient = client
}

// CreateGoodsIndex 创建商品索引
// 功能: 创建用于存储商品数据的ES索引
// 参数:
//   - indexName: 索引名称
func CreateGoodsIndex(indexName string) error {
	// 检查索引是否已存在
	exists, err := ESClient.Indices.Exists([]string{indexName})
	if err != nil {
		return fmt.Errorf("failed to check index existence: %w", err)
	}
	defer exists.Body.Close()

	// 如果索引已存在，则删除它
	if exists.StatusCode == 200 {
		deleteRes, err := ESClient.Indices.Delete([]string{indexName})
		if err != nil {
			return fmt.Errorf("failed to delete existing index: %w", err)
		}
		defer deleteRes.Body.Close()
		if deleteRes.IsError() {
			return fmt.Errorf("error deleting index: %s", deleteRes.Status())
		}
	}

	// 创建新索引
	createRes, err := ESClient.Indices.Create(
		indexName,
		ESClient.Indices.Create.WithBody(strings.NewReader(`{
		  "settings": {
			"number_of_shards": 1,
			"number_of_replicas": 0
		  },
		  "mappings": {
			"properties": {
			  "id": {
				"type": "integer"
			  },
			  "title": {
				"type": "text",
				"analyzer": "ik_max_word",
				"search_analyzer": "ik_smart"
			  },
			  "image": {
				"type": "keyword"
			  },
			  "good_price": {
				"type": "double"
			  },
			  "good_stock": {
				"type": "integer"
			  },
			  "good_status": {
				"type": "integer"
			  },
			  "create_time": {
				"type": "date"
			  },
			  "update_time": {
				"type": "date"
			  }
			}
		  }
		}`)),
	)
	if err != nil {
		return fmt.Errorf("failed to create index: %w", err)
	}
	defer createRes.Body.Close()

	if createRes.IsError() {
		return fmt.Errorf("error creating index: %s", createRes.Status())
	}

	log.Printf("Index %s created successfully", indexName)
	return nil
}
